import React from 'react';
import { router } from 'umi';
import { connect } from 'dva';
import { getComponent } from '@/utils/utils';
import styles from './index.less';

const ToPage = (props: any) => {
    const {
        name,
        children,
        global: { tabList = [], routeList = [] },
        dispatch
    } = props;

    const onClick = () => {
        const isExit = tabList.filter((tabItem: any) => tabItem.key === name).length;
        const menuItem: any = getComponent(name, routeList) || {};
        if (!isExit) {
            tabList.push({
                key: name,
                title: menuItem.title,
                content: menuItem.component
            });
            dispatch({
                type: 'global/save',
                payload: {
                    tabList
                }
            });
        }
        dispatch({
            type: 'global/save',
            payload: {
                activeKey: name
            }
        });
        router.replace(menuItem.path);
    };

    return (
        <div className={styles.toPage} onClick={onClick}>
            {children}
        </div>
    );
};

export default connect(({ global }: any) => ({
    global
}))(ToPage);
